﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using Citi.PTSConsolidation.Domain.Utils;
using Citi.PTSConsolidation.SchedulerUI.SchedulerWcf;
using Citi.PTSConsolidation.SchedulerUI.Util;
using Citi.RoutineBase;

namespace Citi.PTSConsolidation.SchedulerUI
{
    public class ValidatePearlAccountMap : IExecutableRoutine
    {
        private static string PtsConnectionString { get { return ConfigurationManager.AppSettings["PtsConnectionString"]; } }
        private string PtsUrl { get { return ConfigurationManager.AppSettings["PtsUrl"]; } }

        public IEnumerable<RoutineParameter> Parameters
        {
            get
            {
                return new List<RoutineParameter>{
                    new RoutineParameter { Description = "If you want to start a routine when it's finished, insert the Routine Id.", Name = "SuccessorRoutineId",                        
                        Nullable = false, Required = true, Type = typeof(int) },
                    new RoutineParameter{ Description = "Users to send email about new account", Name ="EmailUsers", Nullable = false, Required = true, Type = typeof(string)}
                };
            }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            UpdatePtsLine(currentAction);
            ValidatePtsLineBlank(currentAction, parameters);
        }

        private void ValidatePtsLineBlank(ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            currentAction.Description = "Checking No Mapped accounts";
            var query = Domain.PearlAccountMap.QueryNoMapped;
            currentAction.Description = query;
            var accounts = SqlHelper.ExecuteReader(query, PtsConnectionString);

            if (accounts.Rows.Count == 0)
            {
                currentAction.Description = "Exceptions not found";
                var successorRoutineId = int.Parse(parameters["SuccessorRoutineId"].ToString());

                using (var client = new ScheduleClient())
                    client.ExecuteRoutineOnDemandById(successorRoutineId, new Dictionary<string, string>());

                return;
            }
            else
                currentAction.Description = "Exceptions found";

            SendExceptionEmail(parameters, accounts);
        }

        private static void UpdatePtsLine(ICurrentAction currentAction)
        {
            currentAction.Description = "Updating PTS Line";
            var query = "EXEC [sp_PearlAccountNonMapped]";
            currentAction.Description = query;
            SqlHelper.ExecuteNonQuery(query, PtsConnectionString);
            currentAction.Description = "Updated";
        }

        private void SendExceptionEmail(Dictionary<string, object> parameters, DataTable accounts)
        {
            var emailUsers = parameters["EmailUsers"].ToString().Split(new[] { ';' }).ToList();
            var htmlTable = string.Empty;

            foreach (DataRow row in accounts.Rows)
            {
                htmlTable += string.Format(@"<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
                row["AccountL14Desc"].ToString(), row["Leaf"].ToString(), row["LeafDescr"].ToString());
            }

            var emailParameters = new Dictionary<string, string>();
            emailParameters.Add("[Accounts]", htmlTable);
            emailParameters.Add("[AssociateLink]", string.Format("{0}/PearlAccountMap/Exceptions", PtsUrl));

            EmailSenderHelper.SendEmailWithTemplate(emailUsers, null, null, 3034, emailParameters);
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }
    }
}
